﻿/* ----------------------------------------------------------------------------
 * Copyright (c) Philip Stears 
 *
 * This source code is subject to terms and conditions of the Microsoft Public 
 * License (Ms-PL).
 * 
 * By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 * 
 * To request a copy of the Microsoft Public License, send a request by email
 * to license@connectbasic.net.
 *
 * This notice must not be removed from this software.
 * ---------------------------------------------------------------------------- */

namespace ConnectBasic.Execution
{
    using System;
    using System.Collections.Generic;
    using ConnectDebug;

    internal static class BasicRuntimeHelpers
    {

        /// <summary>
        /// Instantiates a new BASIC module.
        /// </summary>
        /// <param name="name">The name of the module.</param>
        /// <param name="functions">The functions which make up the module.</param>
        /// <param name="locals">The locals which make up the module.</param>
        /// <param name="debugger">The debugger proxy for the module.</param>
        /// <returns></returns>
        public static BasicModule MakeModule(string name, IEnumerable<BasicFunction> functions, IEnumerable<LocalDefinition> locals, ProxyDebugger debugger)
        {
            return new BasicModule(name, functions, locals, debugger);
        }

        /// <summary>
        /// Instantiates a new BASIC function.
        /// </summary>
        /// <param name="name">The name of the function.</param>
        /// <param name="code">The code which comprises the function.</param>
        /// <returns></returns>
        public static BasicFunction MakeMethod(string name, Delegate code)
        {
            return new BasicFunction(name, code);
        }

        public static object GetModuleValueCore(BasicModule module, string name)
        {
            object result;

            if (module.TryGetLocalValue(name, out result))
            {
                return result;
            }
            else
            {
                throw new MissingMemberException("<Module>", name);
            }
        }

        public static void SetModuleValueCore(BasicModule module, string name, object value)
        {
            module.SetLocalValue(name, value);
        }

        public static T GetModuleValue<T>(BasicModule module, string name)
        {
            return (T)GetModuleValueCore(module, name);
        }

        public static void SetModuleValue<T>(BasicModule module, string name, T value)
        {
            SetModuleValueCore(module, name, (object)value);
        }
    }
}
